/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import com.icesoft.faces.component.ext.RowSelectorEvent;
import com.icesoft.faces.component.selectinputtext.SelectInputText;
import core.User;
import core.UserLevel;
import db.JDBC.core.UserJdbcDAOCore;
import db.core.interfaces.UserDAOCore;
import db.factories.UserDAOFactory;
import db.interfaces.UserDAO;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

/**
 *
 * @author Administrator
 */
public class UserListBean extends AutoCompleteBean
{

    List<UserBean> userList;
    private UserBean selectedUser;
    private int selectedRow;
    private boolean editMode;
    private String oldSearchString;
    private String newPassword;

    // used for sortable dataTable!


    private final static String idColumnName = "id #";
    private final static String fnameColumnName = "First Name";
    private final static String lnameColumnName = "Last Name";
    private final static String emailColumnName = "e-mail adress";
    private final static String levelColumnName = "level";

    private final static String dbIdColumnName = "id";
    private final static String dbFnameColumnName = "fname";
    private final static String dbLnameColumnName = "lname";
    private final static String dbEmailColumnName = "email";
    private final static String dbLevelColumnName = "level";

    private HashMap<String, String> lookupDbColumnName;

    boolean ascending;
    boolean oldAscending;
    private String sortColumnName;
    private String oldSortColumnName;


    public String getIdColumnName()
    {
        return idColumnName;
    }

    public String getFnameColumnName()
    {
        return fnameColumnName;
    }
    public String getLnameColumnName()
    {
        return lnameColumnName;
    }

    public String getEmailColumnName()
    {
        return emailColumnName;
    }
        public String getLevelColumnName()
    {
        return levelColumnName;
    }


   public void setSortColumnName(String name)
    {
        this.oldSortColumnName = this.sortColumnName;
        this.sortColumnName = name;
    }

    public String getSortColumnName()
    {
        return sortColumnName;
    }

    public void setAscending (boolean ascending)
    {
        oldAscending = this.ascending;
        this.ascending = ascending;
    }

    public boolean getAscending()
    {
        return ascending;
    }

    @PostConstruct
    public void init()
    {
        userList = new ArrayList<UserBean>();
                for(User user: UserJdbcDAOCore.getInstance().getAllUsers())
                {
                    userList.add(new UserBean(user));
                }

        editMode = false;
        oldAscending = ascending = true;
        oldSortColumnName = sortColumnName = idColumnName;
        initDbColumns();
        oldSearchString = "";
        searchString = "";
        newPassword = "";
    }
    private void initDbColumns()
    {
        lookupDbColumnName = new HashMap<String, String>();
        lookupDbColumnName.put(idColumnName, dbIdColumnName);
        lookupDbColumnName.put(fnameColumnName, dbFnameColumnName);
        lookupDbColumnName.put(lnameColumnName, dbLnameColumnName);
        lookupDbColumnName.put(emailColumnName, dbEmailColumnName);
        lookupDbColumnName.put(levelColumnName, dbLevelColumnName);
    }


    public List<UserBean> getUserList()
    {
        if(oldAscending != ascending || !sortColumnName.equals(oldSortColumnName))
        search(null);
        return userList;
    }

    public void setUserList(List<UserBean> userList)
    {
        this.userList = userList;
    }

    public void setSelected(RowSelectorEvent ev)
    {
        this.selectedRow = ev.getRow();
        this.selectedUser = new UserBean(
                userList.get(ev.getRow())
                );
    }

    public UserBean getSelected()
    {
        return selectedUser;
    }

    public boolean getEditMode()
    {
        return editMode;
    }

    public void setEditMode(boolean editMode)
    {

        this.editMode = editMode;
    }

    public void enableEditMode(ActionEvent e)
    {
        if(selectedUser != null)
        {
        editMode = true;
        newPassword = ""; // reset new password
        }
    }

    public void disableEditMode(ActionEvent e)
    {
        editMode = false;
    }

    public void updateUser(ActionEvent e)
    {
        if(!newPassword.equals(""))
        selectedUser.setPassword(newPassword);
        
        UserDAOFactory.getDAO(UserDAOFactory.DAOTYPE.JDBC).editUser(selectedUser.getUser());
        userList.get(selectedRow).setUser(selectedUser.getUser());
        editMode = false;
    }

    public void deleteUser(ActionEvent e)
    {
        UserDAOFactory.getDAO(UserDAOFactory.DAOTYPE.JDBC).deleteUser(selectedUser.getUser());
        userList.remove(selectedRow);
        editMode = false;
    }

    public void search(ActionEvent e)
    {
        UserDAO uDao = UserDAOFactory.getDAO(UserDAOFactory.DAOTYPE.JDBC);
        if (uDao == null) return;

        if(lookupDbColumnName.get(sortColumnName) == null) return;
        
        
        List<UserBean> newUserList;

        newUserList = new ArrayList<UserBean>();

        // new search! Should recieve actionEvent
        if(e != null)
        {
        Collection<User> users = uDao.searchForUsersByParameters(searchString,
                lookupDbColumnName.get(sortColumnName), ascending);
                if(users!=null)
                    for(User user: users)
                        newUserList.add(new UserBean(user));

                    oldSearchString = searchString;

        }
        else
        {// AcionEvent == null, we do just an update
            // due to ascending
            Collection<User> users = uDao.searchForUsersByParameters(oldSearchString,
                lookupDbColumnName.get(sortColumnName), ascending);
                if(users!=null)
                    for(User user: users)

                        newUserList.add(new UserBean(user));
        }
                    this.userList = newUserList;
                    oldAscending = ascending;
                    oldSortColumnName = sortColumnName;

    }

    public void showAll(ActionEvent e)
    {
        this.oldSearchString = "";
        search(null);
    }
    public void selectInputValueChanged(ValueChangeEvent event)
    {
        if (event.getComponent() instanceof SelectInputText)
        {
            SelectInputText autoComplete = (SelectInputText) event.getComponent();
            String newWord = (String) event.getNewValue();
            matchPossibilities = generateMatches(newWord, 10);

            if (autoComplete.getSelectedItem() != null)
                searchString = (String) autoComplete.getSelectedItem().getValue();
        }
    }
    public List<SelectItem> generateMatches(String searchWord, int maxMatches)
    {
        ArrayList<String> matchList = new ArrayList();
        List<SelectItem> returnCollection = new ArrayList<SelectItem>();

        if ((searchWord == null) || (searchWord.trim().length() == 0))
            return returnCollection;

        UserDAOCore userDAO = UserJdbcDAOCore.getInstance();

        for(String s : userDAO.searchForStringUsers(searchWord, maxMatches))
            matchList.add(s);
        Collections.sort(matchList);

        if(matchList.size() < maxMatches)
            maxMatches = matchList.size();

        for(String s : matchList.subList(0, maxMatches))
            returnCollection.add(new SelectItem(s));
        return returnCollection;
    }

    public List<SelectItem> getLevelOption()
    {
        ArrayList list = new ArrayList<SelectItem>();
        for(String option: UserLevel.getUserLevelNames())
            list.add(new SelectItem(option));
        return list;
    }

    public String getNewPassword()
    {
            return newPassword;
    }
    public void setNewPassword(String newPassword)
    {
        this.newPassword = newPassword;
    }

}
